package com.wyh.controller.groupOne.customer;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageInfo;
import com.wyh.common.enums.ResultCodeEnum;
import com.wyh.common.exception.CustomException;
import com.wyh.common.result.Result;
import com.wyh.domain.po.groupOne.customer.MasterDataContacts;
import com.wyh.domain.vo.groupOne.customer.CustomerAccuratelyVO;
import com.wyh.domain.vo.groupOne.customer.MasterDataCustomerVO;
import com.wyh.service.groupOne.customer.MasterDataCCustomerService;
import com.wyh.service.groupOne.customer.MasterDataContactsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("masterDataCustomer")
@Api(tags = "客户管理API")
public class CCustomerController {

    @Resource
    private MasterDataCCustomerService masterDataCCustomerService;

    @Resource
    private MasterDataContactsService masterDataContactsService;


    /**
     * 查询所有客户
     *
     * @param customer
     * @return
     */
    @ApiOperation(value = "get-查询所有客户")
    @GetMapping("/selectAll")
    public Result selectAll(MasterDataCustomerVO customer) {
        if (customer == null) {
            throw new CustomException(ResultCodeEnum.PARAM_LOST_ERROR);
        }
        List<MasterDataCustomerVO> customers = masterDataCCustomerService.selectAll(customer);
        return Result.success(customers);
    }

    /**
     * 精准查询
     */
    @ApiOperation(value = "get-精准查询客户")
    @GetMapping("/selectAccurately")
    public Result selectAccurately(CustomerAccuratelyVO customer) {
        if (ObjectUtil.isAllEmpty(customer.getName(), customer.getLnvolvinglitigation(), customer.getType(), customer.getTelephone())) {
            throw new CustomException(ResultCodeEnum.PARAM_LOST_ERROR);
        }
        List<MasterDataCustomerVO> dbcustomer = masterDataCCustomerService.selectAccurately(customer);
        if (ObjectUtil.isEmpty(dbcustomer)) {
            return Result.error(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        return Result.success(dbcustomer);
    }

    /**
     * 分页精准查询
     */
    @ApiOperation(value = "get-分页精准查询")
    @GetMapping("/selectPage")
    public Result selectPage(CustomerAccuratelyVO customer,
                             @RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        if (ObjectUtil.isAllEmpty(customer.getName(), customer.getLnvolvinglitigation(), customer.getType(), customer.getTelephone())) {
            throw new CustomException(ResultCodeEnum.PARAM_LOST_ERROR);
        }
        PageInfo<MasterDataCustomerVO> page = masterDataCCustomerService.selectPage(customer, pageNum, pageSize);
        if (ObjectUtil.isEmpty(page)) {
            return Result.error(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        return Result.success(page);

    }


    /**
     * 新增客户
     *
     * @param customer
     * @return
     */
    @ApiOperation(value = "post-新增客户")
    @Transactional
    @PostMapping("add")
    public Result insert(@RequestBody @Validated MasterDataCustomerVO customer) {

        List<MasterDataContacts> masterDataContactsList = customer.getMasterDataContactsList();
        List<MasterDataContacts> dbcontactsList = masterDataContactsService.selectByCustomerId(customer.getId());
        if (customer.getUserid() == null) {
            throw new CustomException(ResultCodeEnum.OPERATION_AUTHORITY_ERROR);
        }

        int code = masterDataCCustomerService.insert(customer);
        if (code != 0) {
            //contacts遍历数组
            if (ObjectUtil.isNotEmpty(masterDataContactsList)) {
                // 检查联系人数量是否超过5个
                if ((masterDataContactsList.size() + dbcontactsList.size()) > 5) {
                    throw new CustomException("400", "只能添加5个联系人");
                }
                for (MasterDataContacts masterDataContacts : masterDataContactsList) {
                    // 对联系人名称和电话进行格式校验
                    if (masterDataContacts.getName().length() < 4 || masterDataContacts.getName().length() > 50 ||
                            masterDataContacts.getTelephone().length() < 4 || masterDataContacts.getTelephone().length() > 11) {
                        throw new CustomException("400", "联系人名称和电话格式不符合要求");
                    }

                    //联系人的customerid为当期的客户id
                    masterDataContacts.setCustomerid(String.valueOf(customer.getId()));

                    // 插入新的联系人对象
                    if (masterDataContacts.getCustomerid() != null) {
                        masterDataContactsService.insert(masterDataContacts);
                    } else {
                        return Result.error("400", "联系人添加失败");
                    }
                }

            }
            return Result.success();
        } else {
            return Result.error("400", "添加失败");
        }

    }


    /**
     * 查看客户详情--基础信息
     */
    @ApiImplicitParam(name = "id", value = "客户id", required = true)
    @ApiOperation(value = "get-查看客户详情--基础信息")
    @GetMapping("selectDetailBasic/{id}")
    public Result selectDetailBasic(@PathVariable Integer id) {

        MasterDataCustomerVO dbcustomer = masterDataCCustomerService.selectDetailBasic(id);
        List<MasterDataContacts> masterDataContactsList = masterDataContactsService.selectAll(id);
        if (!masterDataContactsList.isEmpty()) {
            dbcustomer.setMasterDataContactsList(masterDataContactsList);
        }
        return Result.success(dbcustomer);
    }


    /**
     * 编辑客户信息
     *
     * @param masterDataCustomerVO
     * @return
     */
    @ApiOperation(value = "post-编辑客户信息")
    @PostMapping("update")
    @Transactional
    public Result update(@RequestBody @Validated MasterDataCustomerVO masterDataCustomerVO) {
        if (masterDataCustomerVO.getId() != null && masterDataCustomerVO.getUserid() != null) {
            List<MasterDataContacts> dbcontactsList = masterDataContactsService.selectByCustomerId(masterDataCustomerVO.getId());//数据库里的联系人
            List<MasterDataContacts> masterDataContactsList = masterDataCustomerVO.getMasterDataContactsList();
            int code = masterDataCCustomerService.update(masterDataCustomerVO);
            if (code != 0) { //判断客户是否修改成功，若联系人成功，客户失败，则也失败
                if (!masterDataContactsList.isEmpty()) {
                    for (MasterDataContacts dbMasterDataContacts : dbcontactsList) {
                        boolean existsInNewList = false;
                        for (MasterDataContacts masterDataContacts : masterDataContactsList) {
                            if (masterDataContacts.getId() == null) {
                                throw new CustomException("400", "联系人id不能为空");
                            }
                            if (dbMasterDataContacts.getId().equals(masterDataContacts.getId())) { // 如果dbContacts在新的列表中存在
                                existsInNewList = true;
                                masterDataContactsService.update(masterDataContacts);
                                break;
                            }
                        }
                        if (!existsInNewList) { // 如果dbContacts在新的列表中不存在，则删除
                            // 这里执行删除逻辑
                            masterDataContactsService.delete(dbMasterDataContacts.getId()); // 假设有一个根据联系人ID删除联系人的方法
                        }
                    }
                }
                return Result.success(ResultCodeEnum.UPDATE_SUCCESS);
            } else {
                return Result.error(ResultCodeEnum.ORGANIZATION_UPDATE_ERROR);
            }
        }
        return Result.error(ResultCodeEnum.OPERATION_AUTHORITY_ERROR);
    }

    /**
     * 停用-启用
     *
     * @param masterDataCustomerVO
     * @return
     */
    @ApiOperation(value = "post-状态停用-启用")
    @PostMapping("updateState")
    public Result updateState(@RequestBody MasterDataCustomerVO masterDataCustomerVO) {
        if (masterDataCustomerVO.getId() != null && masterDataCustomerVO.getUserid() != null) {
            masterDataCCustomerService.updateState(masterDataCustomerVO);
            return Result.success();
        }
        return Result.error(ResultCodeEnum.OPERATION_AUTHORITY_ERROR);
    }

    /**
     * 涉诉
     *
     * @return
     */
    @ApiOperation(value = "post-涉诉")
    @PostMapping("updateLitigation")
    public Result updateLitigation(@RequestBody MasterDataCustomerVO masterDataCustomerVO) {
        if (masterDataCustomerVO.getId() != null && masterDataCustomerVO.getUserid() != null) {
            MasterDataCustomerVO dbcustomer = masterDataCCustomerService.selectDetailBasic(masterDataCustomerVO.getId());
            if (!ObjectUtils.isEmpty(dbcustomer)) {
                DateTime date = DateUtil.date();
                masterDataCustomerVO.setLastupdatetime(date.toString());
                masterDataCCustomerService.update(masterDataCustomerVO);
                return Result.success();
            }

        }
        return Result.error(ResultCodeEnum.ORGANIZATION_UPDATE_ERROR);
    }

    /**
     * 根据客户姓名、电话或证件号查询
     *
     * @param input
     * @return
     */
    @ApiOperation(value = "get-根据客户姓名、电话或证件号查询（其余业务中使用）")
    @GetMapping("selectByOther/{input}")
    public Result selectByOther(@PathVariable String input) {
        List<MasterDataCustomerVO> masterDataCustomerVOS = masterDataCCustomerService.selectByOther(input);
        if (!ObjectUtils.isEmpty(masterDataCustomerVOS)) {
            return Result.success(masterDataCustomerVOS);
        }
        return Result.error(ResultCodeEnum.USER_NOT_EXIST_ERROR);
    }


}
